using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

public class RemoteHostForm : Form
{
    private readonly UpdateManager updateManager;
    private readonly Action<string, Color?> logAction;
    
    private ComboBox hostComboBox;
    private Button addHostButton;
    private Button editHostButton;
    private Button deleteHostButton;
    private Button loadIISButton;
    private ListView iisListView;
    private Label statusLabel;
    private ProgressBar progressBar;
    
    private RemoteDesktopManager rdpManager;
    private RemoteConnectionResult? currentConnection;

    public RemoteHostForm(UpdateManager manager, Action<string, Color?> logCallback)
    {
        updateManager = manager;
        logAction = logCallback;
        rdpManager = new RemoteDesktopManager();
        
        InitializeComponent();
        LoadRemoteHosts();
    }

    private void InitializeComponent()
    {
        Text = "远程主机管理";
        Size = new Size(900, 600);
        StartPosition = FormStartPosition.CenterParent;
        FormBorderStyle = FormBorderStyle.Sizable;

        // 远程主机选择区域
        var hostLabel = new Label { Text = "远程主机:", Location = new Point(10, 15), Size = new Size(70, 20) };
        Controls.Add(hostLabel);

        hostComboBox = new ComboBox 
        { 
            Location = new Point(90, 13), 
            Size = new Size(250, 25),
            DropDownStyle = ComboBoxStyle.DropDownList
        };
        Controls.Add(hostComboBox);

        addHostButton = new Button { Text = "添加", Location = new Point(350, 12), Size = new Size(60, 25) };
        addHostButton.Click += AddHostButton_Click;
        Controls.Add(addHostButton);

        editHostButton = new Button { Text = "编辑", Location = new Point(420, 12), Size = new Size(60, 25) };
        editHostButton.Click += EditHostButton_Click;
        Controls.Add(editHostButton);

        deleteHostButton = new Button { Text = "删除", Location = new Point(490, 12), Size = new Size(60, 25) };
        deleteHostButton.Click += DeleteHostButton_Click;
        Controls.Add(deleteHostButton);

        loadIISButton = new Button { Text = "加载IIS站点", Location = new Point(560, 12), Size = new Size(100, 25) };
        loadIISButton.Click += LoadIISButton_Click;
        Controls.Add(loadIISButton);

        // 状态标签
        statusLabel = new Label 
        { 
            Text = "请选择远程主机", 
            Location = new Point(10, 45), 
            Size = new Size(860, 20),
            ForeColor = Color.Gray
        };
        Controls.Add(statusLabel);

        // IIS站点列表
        var iisLabel = new Label { Text = "IIS站点列表:", Location = new Point(10, 75), Size = new Size(100, 20) };
        Controls.Add(iisLabel);

        iisListView = new ListView
        {
            Location = new Point(10, 100),
            Size = new Size(860, 400),
            View = View.Details,
            FullRowSelect = true,
            GridLines = true,
            CheckBoxes = true
        };
        iisListView.Columns.Add("站点名称", 150);
        iisListView.Columns.Add("状态", 80);
        iisListView.Columns.Add("端口", 60);
        iisListView.Columns.Add("物理路径", 300);
        iisListView.Columns.Add("绑定信息", 200);
        Controls.Add(iisListView);

        // 进度条
        progressBar = new ProgressBar
        {
            Location = new Point(10, 510),
            Size = new Size(860, 20),
            Style = ProgressBarStyle.Marquee,
            Visible = false
        };
        Controls.Add(progressBar);

        // 关闭按钮
        var closeButton = new Button { Text = "关闭", Location = new Point(800, 540), Size = new Size(70, 25) };
        closeButton.Click += (s, e) => Close();
        Controls.Add(closeButton);
    }

    private void LoadRemoteHosts()
    {
        hostComboBox.Items.Clear();
        var machines = updateManager.GetRemoteMachines();
        
        foreach (var machine in machines)
        {
            hostComboBox.Items.Add(new ComboBoxItem { Text = $"{machine.Name} ({machine.IPAddress})", Value = machine });
        }

        if (hostComboBox.Items.Count > 0)
            hostComboBox.SelectedIndex = 0;
    }

    private void AddHostButton_Click(object sender, EventArgs e)
    {
        using var dialog = new RemoteHostEditDialog(null);
        if (dialog.ShowDialog(this) == DialogResult.OK)
        {
            var machine = dialog.GetMachine();
            updateManager.AddRemoteMachine(machine);
            LoadRemoteHosts();
            logAction?.Invoke($"已添加远程主机: {machine.Name}", Color.Green);
        }
    }

    private void EditHostButton_Click(object sender, EventArgs e)
    {
        if (hostComboBox.SelectedItem is ComboBoxItem item && item.Value is RemoteMachine machine)
        {
            using var dialog = new RemoteHostEditDialog(machine);
            if (dialog.ShowDialog(this) == DialogResult.OK)
            {
                var updatedMachine = dialog.GetMachine();
                updateManager.UpdateRemoteMachine(updatedMachine);
                LoadRemoteHosts();
                logAction?.Invoke($"已更新远程主机: {updatedMachine.Name}", Color.Green);
            }
        }
        else
        {
            MessageBox.Show("请选择要编辑的远程主机", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }

    private void DeleteHostButton_Click(object sender, EventArgs e)
    {
        if (hostComboBox.SelectedItem is ComboBoxItem item && item.Value is RemoteMachine machine)
        {
            var result = MessageBox.Show($"确定要删除远程主机 '{machine.Name}' 吗?", "确认删除", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            
            if (result == DialogResult.Yes)
            {
                updateManager.DeleteRemoteMachine(machine.Id);
                LoadRemoteHosts();
                iisListView.Items.Clear();
                statusLabel.Text = "请选择远程主机";
                logAction?.Invoke($"已删除远程主机: {machine.Name}", Color.Green);
            }
        }
        else
        {
            MessageBox.Show("请选择要删除的远程主机", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }

    private async void LoadIISButton_Click(object sender, EventArgs e)
    {
        if (!(hostComboBox.SelectedItem is ComboBoxItem item) || !(item.Value is RemoteMachine machine))
        {
            MessageBox.Show("请选择远程主机", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }

        SetUIEnabled(false);
        progressBar.Visible = true;
        statusLabel.Text = $"正在连接到 {machine.Name}...";
        statusLabel.ForeColor = Color.Blue;
        iisListView.Items.Clear();

        var progress = new Progress<string>(message =>
        {
            statusLabel.Text = message;
            logAction?.Invoke($"[远程连接] {message}", null);
        });

        try
        {
            currentConnection = await rdpManager.ConnectAndLoadIISServices(machine, progress);

            if (currentConnection.IsConnected)
            {
                statusLabel.Text = $"已连接 - 发现 {currentConnection.IISServices.Count} 个IIS站点";
                statusLabel.ForeColor = Color.Green;

                foreach (var service in currentConnection.IISServices)
                {
                    var listItem = new ListViewItem(service.SiteName);
                    listItem.SubItems.Add(service.State);
                    listItem.SubItems.Add(service.Port.ToString());
                    listItem.SubItems.Add(service.PhysicalPath);
                    listItem.SubItems.Add(service.Bindings);
                    listItem.Tag = service;

                    if (service.State.ToLower().Contains("start"))
                        listItem.ForeColor = Color.Green;
                    else if (service.State.ToLower().Contains("stop"))
                        listItem.ForeColor = Color.Red;

                    iisListView.Items.Add(listItem);
                }

                logAction?.Invoke($"成功加载 {currentConnection.IISServices.Count} 个IIS站点", Color.Green);
            }
            else
            {
                statusLabel.Text = $"连接失败: {currentConnection.ErrorMessage}";
                statusLabel.ForeColor = Color.Red;
                logAction?.Invoke($"连接失败: {currentConnection.ErrorMessage}", Color.Red);
                MessageBox.Show($"连接失败:\n\n{currentConnection.ErrorMessage}\n\n请检查:\n1. 远程主机是否开启WinRM服务\n2. 网络连接是否正常\n3. 用户名密码是否正确", 
                    "连接失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        catch (Exception ex)
        {
            statusLabel.Text = $"连接异常: {ex.Message}";
            statusLabel.ForeColor = Color.Red;
            logAction?.Invoke($"连接异常: {ex.Message}", Color.Red);
            MessageBox.Show($"连接异常:\n\n{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {
            progressBar.Visible = false;
            SetUIEnabled(true);
        }
    }

    private void SetUIEnabled(bool enabled)
    {
        hostComboBox.Enabled = enabled;
        addHostButton.Enabled = enabled;
        editHostButton.Enabled = enabled;
        deleteHostButton.Enabled = enabled;
        loadIISButton.Enabled = enabled;
    }

    private class ComboBoxItem
    {
        public string Text { get; set; } = "";
        public object? Value { get; set; }
        public override string ToString() => Text;
    }
}

public class RemoteHostEditDialog : Form
{
    private TextBox nameTextBox;
    private TextBox ipTextBox;
    private TextBox portTextBox;
    private TextBox usernameTextBox;
    private TextBox passwordTextBox;
    private TextBox descriptionTextBox;
    
    private RemoteMachine? originalMachine;

    public RemoteHostEditDialog(RemoteMachine? machine)
    {
        originalMachine = machine;
        InitializeComponent();
        
        if (machine != null)
        {
            nameTextBox.Text = machine.Name;
            ipTextBox.Text = machine.IPAddress;
            portTextBox.Text = machine.Port.ToString();
            usernameTextBox.Text = machine.Username;
            passwordTextBox.Text = machine.Password;
            descriptionTextBox.Text = machine.Description;
        }
    }

    private void InitializeComponent()
    {
        Text = originalMachine == null ? "添加远程主机" : "编辑远程主机";
        Size = new Size(400, 320);
        StartPosition = FormStartPosition.CenterParent;
        FormBorderStyle = FormBorderStyle.FixedDialog;
        MaximizeBox = false;
        MinimizeBox = false;

        var nameLabel = new Label { Text = "主机名称:", Location = new Point(10, 20), Size = new Size(80, 20) };
        nameTextBox = new TextBox { Location = new Point(100, 18), Size = new Size(260, 25) };
        
        var ipLabel = new Label { Text = "IP地址:", Location = new Point(10, 55), Size = new Size(80, 20) };
        ipTextBox = new TextBox { Location = new Point(100, 53), Size = new Size(260, 25) };
        
        var portLabel = new Label { Text = "端口:", Location = new Point(10, 90), Size = new Size(80, 20) };
        portTextBox = new TextBox { Location = new Point(100, 88), Size = new Size(100, 25), Text = "8080" };
        
        var userLabel = new Label { Text = "用户名:", Location = new Point(10, 125), Size = new Size(80, 20) };
        usernameTextBox = new TextBox { Location = new Point(100, 123), Size = new Size(260, 25) };
        
        var passLabel = new Label { Text = "密码:", Location = new Point(10, 160), Size = new Size(80, 20) };
        passwordTextBox = new TextBox { Location = new Point(100, 158), Size = new Size(260, 25), UseSystemPasswordChar = true };
        
        var descLabel = new Label { Text = "备注:", Location = new Point(10, 195), Size = new Size(80, 20) };
        descriptionTextBox = new TextBox { Location = new Point(100, 193), Size = new Size(260, 25) };
        
        var okButton = new Button { Text = "确定", Location = new Point(200, 240), Size = new Size(75, 30) };
        okButton.Click += OkButton_Click;
        
        var cancelButton = new Button { Text = "取消", Location = new Point(285, 240), Size = new Size(75, 30) };
        cancelButton.Click += (s, e) => DialogResult = DialogResult.Cancel;

        Controls.AddRange(new Control[] 
        { 
            nameLabel, nameTextBox, ipLabel, ipTextBox, portLabel, portTextBox,
            userLabel, usernameTextBox, passLabel, passwordTextBox, descLabel, descriptionTextBox,
            okButton, cancelButton 
        });
    }

    private void OkButton_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrWhiteSpace(nameTextBox.Text))
        {
            MessageBox.Show("请输入主机名称", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }

        if (string.IsNullOrWhiteSpace(ipTextBox.Text))
        {
            MessageBox.Show("请输入IP地址", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }

        if (!int.TryParse(portTextBox.Text, out int port) || port <= 0 || port > 65535)
        {
            MessageBox.Show("请输入有效的端口号(1-65535)", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }

        if (string.IsNullOrWhiteSpace(usernameTextBox.Text))
        {
            MessageBox.Show("请输入用户名", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }

        DialogResult = DialogResult.OK;
    }

    public RemoteMachine GetMachine()
    {
        return new RemoteMachine
        {
            Id = originalMachine?.Id ?? Guid.NewGuid().ToString(),
            Name = nameTextBox.Text.Trim(),
            IPAddress = ipTextBox.Text.Trim(),
            Port = int.Parse(portTextBox.Text),
            Username = usernameTextBox.Text.Trim(),
            Password = passwordTextBox.Text,
            Description = descriptionTextBox.Text.Trim()
        };
    }
}
